package com.zzc.mcpclient.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SSEServer {
    private static final Map<Long, SseEmitter> SSE_EMITTER_MAP = new ConcurrentHashMap<>();

    public static SseEmitter connect(Long userId){
        SseEmitter sseEmitter = new SseEmitter(0L);
        // 发送完成
        sseEmitter.onCompletion(() ->{
            log.info("SSE发送完成");
        });
        sseEmitter.onTimeout(() ->{
            log.error("SSE连接超时");
            SSE_EMITTER_MAP.remove(userId);
        });
        sseEmitter.onError((Throwable throwable) ->{
            log.error("SSE连接错误：{}", throwable.getMessage());
            SSE_EMITTER_MAP.remove(userId);
        });
        SSE_EMITTER_MAP.put(userId, sseEmitter);
        return sseEmitter;
    }

    public static void sendEmitterMessage(SseEmitter sseEmitter, Long userId, String message, String msgType) {
        try {
            SseEmitter.SseEventBuilder msgEvent = SseEmitter.event()
                    .id(userId+"")
                    .data(message)
                    .name(msgType);
            sseEmitter.send(msgEvent);
        } catch (IOException e) {
            log.error("SSE异常...{}", e.getMessage());
            SSE_EMITTER_MAP.put(userId, sseEmitter);
        }

    }
}
